import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:gate_cli/exception/errors.dart';
import 'package:gate_cli/utils/command_util.dart';
import 'package:gate_cli/utils/file_util.dart';
import 'package:gate_cli/utils/print.dart';
import 'package:gate_cli/utils/process_util.dart';
import 'package:gate_cli/utils/pubspec_uitl.dart';
import 'package:gate_cli/utils/string_extension.dart';

/// Author: Shper
/// Created: 2023/9/6
class BuildCommand extends Command<String> {

  BuildCommand() {
    // asset -c config
    argParser.addOption('version', abbr: 'v', defaultsTo: '1', help: '版本号');
    argParser.addOption('platform', abbr: 'p', defaultsTo: 'all', help: '构建产物包的平台');
    argParser.addOption('publishBuild', defaultsTo: "false", help: '是否为正式发布包产物');
    argParser.addOption('buildMode', defaultsTo: 'default', help: '编译模式, default、release、profile、debug');
    argParser.addOption('printLog', defaultsTo: 'false', help: '是否控制台直接输出日志');
    argParser.addOption('verbose', defaultsTo: 'false', help: '是否打印详细日志');
    argParser.addOption('clear', abbr: 'c', defaultsTo: "true", help: '是否执行清除命令');
    argParser.addOption('checkVersion', defaultsTo: "true", help: '是否检查版本号正确');
    argParser.addOption('upload', defaultsTo: "true", help: '是否上传到 Gate Repository');
    argParser.addOption('ignoreFrameworks', defaultsTo: 'true', help: '是否忽略一些iOS三方库构建');
  }

  final flutterCommand = 'flutter';
  // 是否为 正式发布包产物 构建
  var isPublishBuild = false;
  // Maven 地址
  // var releaseMavenUrl = "http://54.168.206.12:8081/repository/dev-mobile-release";
  // var snapshotMavenUrl = "http://54.168.206.12:8081/repository/dev-mobile-snapshot";
  var releaseMavenUrl = "https://nexus-web.fulltrust.link/repository/dev-mobile-release";
  var snapshotMavenUrl = "https://nexus-web.fulltrust.link/repository/dev-mobile-snapshot";

  @override
  String get description => "Flutter产物构建";

  @override
  String get name => "build";

  @override
  FutureOr<String>? run() async {
    var ci = Platform.environment["GT_CI"];
    if (ci != 'ci') {
      throw new CommandRunError('当前不是打包机环境，禁止构建 Flutter 产物');
    }

    var buildPlatform = argResults?['platform'] ?? 'all';
    if (buildPlatform == 'all') {
      printGreen('开始 iOS、Android Flutter 产物物构建');
    } else if (buildPlatform == 'iOS') {
      printGreen('开始 iOS Flutter 产物物构建');
    } else if (buildPlatform == 'android') {
      printGreen('开始 Android Flutter 产物物构建');
    } else {
      throw new CommandRunError('暂时不支持 $buildPlatform 产物构建');
    }
    print('');

    // 获取当前 分支名
    var currentBranchName = ProcessUtil.runProcessAndResult('git', ['rev-parse', '--abbrev-ref','HEAD']) as String;
    if (currentBranchName.isNullOrEmpty) {
      throw new CommandRunError('获取分支失败，请检测 git 配置');
    }
    currentBranchName = currentBranchName.trim();
    printGreen('currentBranchName: $currentBranchName');

    // master、release、release_XXX 的分支才能打包 release 产物
    var androidVersionSuffix = "";
    var iOSVersionSuffix = "";

    if (currentBranchName == 'master'
        || currentBranchName == 'release' || currentBranchName.startsWith('release')
        || currentBranchName == 'develop' || currentBranchName.startsWith('dev/')) {
      // master、release、develop dev/ 分支可以打 正式产物 和 测试产物
      isPublishBuild = (argResults?['publishBuild'] ?? 'true') == 'true';
    } else {
      // 非 master、release、develop 分支不能打 release 版本的产物
      isPublishBuild = false;
    }

    // Maven 地址，默认 release 地址
    var mavenUrl = releaseMavenUrl;

    // 非正式发布包构建，版本号后缀增加 分支信息
    if (!isPublishBuild) {
      // 非正式包，使用 snapshot 地址
      mavenUrl = snapshotMavenUrl;

      // 根据分支配置 版本号后缀
      var versionBranch = currentBranchName;
      if (currentBranchName.startsWith("dev_") || currentBranchName.startsWith("dev/")) {
        versionBranch = currentBranchName.substring('dev_'.length);
      }
      if (currentBranchName.startsWith("feature_") || currentBranchName.startsWith("feature/")) {
        versionBranch = currentBranchName.substring('feature_'.length);
      }
      // 去除一些特殊的符号
      versionBranch = versionBranch.replaceAll('/', '');
      versionBranch = versionBranch.replaceAll('_', '');
      versionBranch = versionBranch.replaceAll('-', '');
      versionBranch = versionBranch.replaceAll('.', '');

      // 尝试解析字符串为数字
      num? parsed = num.tryParse(versionBranch);
      // 如果解析成功，则说明是纯数字，纯数字时，拼接上 dev 版本后缀
      if (parsed != null) {
        versionBranch = 'dev';
      }

      // // release 分支后缀关键字 特殊处理
      // if (versionBranch == 'release') {
      //   versionBranch = 'rel';
      // }

      // 获取参数中的版本号
      var argVersionSuffix = argResults?['version'] ?? "1";
      // 设置 iOS 版本后缀
      iOSVersionSuffix = ".${versionBranch}.${argVersionSuffix}";

      // 设置 Android 版本后缀
      androidVersionSuffix= ".${versionBranch}-SNAPSHOT";
    }

    // 读取 pubspec.yaml 文件中配置
    var pubspec = CommandUtil.loadConfig('pubspec.yaml');

    // 获取项目中 yaml 文件上配置的版本号
    var version = pubspec['version'];
    if (version == null || version.isEmpty) {
      throw new CommandRunError('版本号异常,请检查版本号参数配置');
    }

    // 处理 +1、+2、+3 等版本号
    version = '${version}'.replaceAll("+", ".");

    var iOSVersion = '${version}${iOSVersionSuffix}';
    var androidVersion  = '${version}${androidVersionSuffix}';

    // 是否发布包
    printGreen('isPublishBuild: $isPublishBuild');
    // 是否上传到远程仓库，默认 true
    var uploadType = argResults?['upload'] ?? 'true';
    bool isUpload = uploadType.toLowerCase() == 'true';
    printGreen('isUpload: $isUpload');

    // 编译模式
    var buildMode = argResults?['buildMode'] ?? 'default';
    printGreen('buildMode: $buildMode');

    // 是否控制台直接输出日志
    var printLogType = argResults?['printLog'] ?? 'false';
    bool isPrintLog = printLogType.toLowerCase() == 'true';
    printGreen('printLog: $isPrintLog');

    // 是否打印详细日志
    var verboseType = argResults?['verbose'] ?? 'false';
    bool verbose = verboseType.toLowerCase() == 'true';
    printGreen('verbose: $verbose');

    // 是否忽略一些iOS三方库构建
    var ignoreFrameworksType = argResults?['ignoreFrameworks'] ?? 'true';
    bool isIgnoreFrameworks = ignoreFrameworksType.toLowerCase() == 'true';

    printGreen('buildPlatform: $buildPlatform');
    if (buildPlatform == 'all' || buildPlatform == 'iOS') {
      printGreen('iOSVersion: $iOSVersion');
    }
    if (buildPlatform == 'all' || buildPlatform == 'android') {
      printGreen('AndroidVersion: $androidVersion');
      printGreen('mavenUrl: $mavenUrl');
    }
    print('');

    // 重置项目工程
    await resetProject();
    // 记录 pubspec.lock 文件
    await PubspecUtil.recordsPubspecLockFile();

    // 开始构建 Android
    if (buildPlatform == 'android' || buildPlatform == 'all') {
      await buildAAR(androidVersion, mavenUrl, buildMode, isUpload, isPrintLog, verbose);
      printGreen("Android 请依赖: $androidVersion 版本");
    }
    // 开始构建 iOS
    if (buildPlatform == 'iOS' || buildPlatform == 'all') {
      await buildXCFramework(iOSVersion, buildMode, isUpload, isPrintLog, verbose, isIgnoreFrameworks);
      printGreen("iOS 请依赖: $iOSVersion 版本");
    }
    if (isUpload) {
      printGreen("🥳 Flutter 产物发布完成~");
    }
    return "Success！";
  }

  /// 重置项目工程
  Future<void> resetProject() async {
    printGreen('Flutter 编译产物清理');
    // 删除缓存build
    final buildDir = Directory("${Directory.current.path}/build/");
    if (buildDir.existsSync()) {
      printGreen('删除 build/ 目录');
      buildDir.deleteSync(recursive: true);
    }

    // 清除 pubspec.lock 文件
    final pubspecLockDir = File("${Directory.current.path}/assets/pubspec.txt");
    if (pubspecLockDir.existsSync()) {
      printGreen('删除 assets/pubspec.txt 文件');
      pubspecLockDir.deleteSync();
    }

    var clearType = argResults?['clear'] ?? 'true';
    if (clearType == 'true') {
      printGreen('');
      printGreen('重置 Flutter pub cache repair');
      // 重置 Flutter pub cache repair
      final pubCacheSuccess = await ProcessUtil.startProcess(flutterCommand, ['pub', 'cache', 'repair']);
      print('Flutter pub cache repair: $pubCacheSuccess');
      if (!pubCacheSuccess) throw new CommandRunError('清除缓存失败，请稍后重试');

      // clean 项目
      final cleanSuccess = await ProcessUtil.startProcess(flutterCommand, ['clean']);
      print('run flutter clean : $cleanSuccess');
      if (!cleanSuccess) throw new CommandRunError('清除缓存失败，请稍后重试');

      printGreen('');
      printGreen('强制更新 pub 依赖');
      // 重新 pub upgrade
      final pubUpgradeSuccess= await ProcessUtil.startProcess(flutterCommand, ["pub", "upgrade"]);
      print('run flutter pub upgrade : $pubUpgradeSuccess');
      if (!pubUpgradeSuccess) throw new CommandRunError('依赖库更新失败，请确认 pubspec.yaml 中的依赖');
    }
  }

  /// 构建 Android 产物
  Future<void> buildAAR(String version, String mavenUrl, String buildMode, bool isUpload, bool isPrintLog, bool verbose) async {
    print("开始构建Android产物 ...");
    // copy build 配置信息
    var cpProcess = await ProcessUtil.startProcess('cp', [
      '-r',
      '${Directory.current.path}/androidCode/build.gradle',
      '${Directory.current.path}/.android/build.gradle'
    ]);
    print('run android build.gradle copy : $cpProcess');
    if (!cpProcess) throw new CommandRunError('android build.gradle 配置不存在，请确认文件是否正常');

    // 构建aar
    var compileParams = [
      'build',
      'aar',
      '--target-platform=android-arm,android-arm64',
      '--build-number',
      version
    ];

    if (buildMode == 'default' || buildMode == 'release') {
      compileParams.add("--no-profile");
      compileParams.add("--no-debug");
    }
    if (buildMode == 'profile') {
      compileParams.add("--no-release");
      compileParams.add("--no-debug");
    }
    if (buildMode == 'debug') {
      compileParams.add("--no-release");
      compileParams.add("--no-profile");
    }

    if (verbose) {
      compileParams.add("--verbose");
    }

    printGreen("flutter $compileParams");

    var aarBuildSuccess = await ProcessUtil.startProcess(flutterCommand, compileParams);
    if (!aarBuildSuccess) throw new CommandRunError('android build.gradle 配置不存在，请确认文件是否正常');

    // 构建成功
    printGreen('Android aar 构建成功');

    if (!isUpload) {
      return;
    }

    //构建成功 查找build文件下所以aar文件
    final aarFiles = findAarFiles(Directory("${Directory.current.path}/build/host/outputs/repo"));
    print('查找build文件下aar文件 ${aarFiles.length}');
    if (aarFiles.isEmpty) throw new CommandRunError('未找到 AAR包');

    for (var file in aarFiles) {
      final item = file.path;
      final resFile = File(item).uri.pathSegments.last;
      // print('item: $item');
      // final result = resFile.contains('flutter_release');

      final length = item.length;
      // final sub = item.substring(0, length - 3);
      // final pom = '$sub.pom';

      final resFileLength = resFile.length;
      final subDir = item.substring(0, length - resFileLength);

      final nameLength = resFile.length;
      final subName = resFile.substring(0, nameLength - 4);

      final filePath = subDir;
      final name = subName;

      //上传 maven
      final deployResult = await runMavenDeploy(version, filePath, name, mavenUrl);
      if (deployResult) {
        print('$name $version 发布完成');
      } else {
        throw new CommandRunError('Android aar MavenPublish 失败');
      }
    }
    print('Android Flutter AAR 包全部发布完成~');
  }

  /// 查找 AAR 包
  List<File> findAarFiles(Directory directory) {
    final aarFiles = <File>[];
    try {
      final list = directory.listSync(recursive: true);
      for (var entity in list) {
        if (entity is File && entity.path.endsWith('.aar')) {
          aarFiles.add(entity);
        }
      }
    } catch (e) {
      throw new CommandRunError('Error while searching for AAR files: $e');
    }
    return aarFiles;
  }

  /// 上传 Maven
  Future<bool> runMavenDeploy(String buildVersion, String filePath, String name, String mavenUrl) async {
    if (!filePath.endsWith('/')) {
      filePath = '${filePath}/';
    }
    var aarFile = '$filePath$name.aar';
    var pomFile = '$filePath$name.pom';
    final mavenArgs = [
      'deploy:deploy-file',
      '-DpomFile=$pomFile',
      '-DgeneratePom=false',
      '-Dfile=$aarFile',
      '-Durl=$mavenUrl',
      '-Dversion=$buildVersion',
      '-DrepositoryId=GateMaven',
      '-Dpackaging=aar'
    ];
    return await ProcessUtil.startProcess('mvn', mavenArgs, printResult: false);
  }

  Future<void> handlePrivacy(String flutterPluginRegistrantPath) async{
    // Directory("$flutterPluginRegistrantPath/Frameworks/web3_wallet.bundle")
    //     .createSync(recursive: true);
    // var cpWeb3BundleSuccess = await ProcessUtil.startProcess('cp', [
    //   '-rf',
    //   '$flutterPluginRegistrantPath/Frameworks/Release/web3_wallet.xcframework/ios-arm64/web3_wallet.framework/web3_wallet.bundle/',
    //   '$flutterPluginRegistrantPath/Frameworks/web3_wallet.bundle'
    // ]);
    var bundles = {
      "web3_wallet.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/web3_wallet.xcframework/ios-arm64/web3_wallet.framework/web3_wallet.bundle/",
      "webview_flutter_wkwebview_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/webview_flutter_wkwebview.xcframework/ios-arm64/webview_flutter_wkwebview.framework/webview_flutter_wkwebview_privacy.bundle/",
      "video_player_avfoundation_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/video_player_avfoundation.xcframework/ios-arm64/video_player_avfoundation.framework/video_player_avfoundation_privacy.bundle/",
      "sqflite_darwin_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/sqflite.xcframework/ios-arm64/sqflite.framework/sqflite_darwin_privacy.bundle/",
      "share_plus_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/share_plus.xcframework/ios-arm64/share_plus.framework/share_plus_privacy.bundle/",
      "package_info_plus_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/package_info_plus.xcframework/ios-arm64/package_info_plus.framework/package_info_plus_privacy.bundle/",
      "flutter_inappwebview_ios_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/flutter_inappwebview_ios.xcframework/ios-arm64/flutter_inappwebview_ios.framework/flutter_inappwebview_ios_privacy.bundle/",
      "device_info_plus_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/device_info_plus.xcframework/ios-arm64/device_info_plus.framework/device_info_plus_privacy.bundle/",
      "OrderedSet_privacy.bundle": "$flutterPluginRegistrantPath/Frameworks/Release/OrderedSet.xcframework/ios-arm64/OrderedSet.framework/OrderedSet_privacy.bundle/",
    };
    List<String> errors = [];
    for (String bundle in bundles.keys){
          Directory("$flutterPluginRegistrantPath/Frameworks/$bundle")
        .createSync(recursive: true);
        final privacyBundle = Directory(bundles[bundle]!);
        if (privacyBundle.existsSync() == false){
          continue;
        }
        var cpBundleSuccess = await ProcessUtil.startProcess('cp', [
          '-rf',
          bundles[bundle]!,
          '$flutterPluginRegistrantPath/Frameworks/$bundle'
        ]);
        if (!cpBundleSuccess){
          errors.add(bundle);
        }
    }

    if (!errors.isEmpty) throw new CommandRunError('Copy Bundle error, errors is ${errors.toString()}');
  }

  /// 构建 iOS 产物
  Future<void> buildXCFramework(String version, String buildMode, bool isUpload, bool isPrintLog, bool verbose, bool isIgnoreFrameworks) async {
    print("开始构建IOS产物 ...");

    final iOSBuildPath = '${Directory.current.path}/build/ios';
    // 删除旧文件
    final iOSBuildDir = Directory(iOSBuildPath);
    if (iOSBuildDir.existsSync()) {
      iOSBuildDir.deleteSync(recursive: true);
    }
    // 删除后重建目录
    iOSBuildDir.createSync(recursive: true);

    // 是否先校验版本号,不符合要求直接退出
    var checkVersionType = argResults?['checkVersion'] ?? 'true';
    if (checkVersionType == 'true') {
      await iosVersionLint(version, iOSBuildPath);
    }

    final flutterPluginRegistrantPath = '$iOSBuildPath/FlutterPluginRegistrant';
    final gtFlutterAppModulePath = '$iOSBuildPath/GTFlutterAppModule';

    // 复制 iOS 配置、源码等文件
    final cpProcess = await ProcessUtil.startProcess("cp", [
      '-f',
      '${Directory.current.path}/iOSCode/Podfile',
      '${Directory.current.path}/.ios/Podfile'
    ]);
    print('run iOS Podfile copy : $cpProcess');
    if (!cpProcess) throw new CommandRunError('Error iOS Podfile copy fail.');

    // 清楚之前老脚步遗留产物
    final oldFrameworks1 = "${Directory.current.path}/iOSCode/FlutterPluginRegistrant/Frameworks";
    if (Directory(oldFrameworks1).existsSync()) {
      Directory(oldFrameworks1).deleteSync(recursive: true);
    }
    final oldFrameworks2 = "${Directory.current.path}/iOSCode/GTFlutterAppModule/Frameworks";
    if (Directory(oldFrameworks2).existsSync()) {
      Directory(oldFrameworks2).deleteSync(recursive: true);
    }

    final cpFlutterPluginRegistrant = await ProcessUtil.startProcess("cp", [
      "-rf",
      "${Directory.current.path}/iOSCode/FlutterPluginRegistrant",
      "$flutterPluginRegistrantPath"]
    );
    print('run iOS FlutterPluginRegistrant copy : $cpProcess');
    if (!cpFlutterPluginRegistrant) throw new CommandRunError('Error iOS FlutterPluginRegistrant copy fail.');

    final cpGTFlutterAppModule = await ProcessUtil.startProcess("cp", [
      "-rf",
      "${Directory.current.path}/iOSCode/GTFlutterAppModule",
      "$gtFlutterAppModulePath"
    ]);
    print('run iOS GTFlutterAppModule copy : $cpProcess');
    if (!cpGTFlutterAppModule) throw new CommandRunError('Error iOS GTFlutterAppModule copy');

    // 编译 Flutter iOS 产物包 ,将日志重定向至 frameworkbuild.log
    var compileParams = [
      "build",
      "ios-framework",
      "--static",
      "--cocoapods",
      // "--no-profile",
      "-o",
      "$flutterPluginRegistrantPath/Frameworks",
      "-i",

    ];

    if (verbose) {
      compileParams.add("--verbose");
    }

    if (buildMode == 'default') {
      compileParams.add("--no-profile");
    }
    if (buildMode == 'release') {
      compileParams.add("--no-profile");
      compileParams.add("--no-debug");
    }
    if (buildMode == 'profile') {
      compileParams.add("--no-release");
      compileParams.add("--no-debug");
    }
    if (buildMode == 'debug') {
      compileParams.add("--no-release");
      compileParams.add("--no-profile");
    }

    // 读取 ignoreFrameworksYaml 配置，删除不需要的组件
    var ignoreFrameworksYaml = CommandUtil.loadConfig('ignore_frameworks.yaml');
    final ignoreFrameworks = ignoreFrameworksYaml['ignoreFrameworks'] ?? [];
    String ignoreParams = jsonEncode(ignoreFrameworks);

    if (isIgnoreFrameworks) {
      compileParams.add("-i");
      compileParams.add("$ignoreParams");
    }

    printGreen("flutter $compileParams");

    if (isPrintLog) {
      var iOSBuilderSuccess = await ProcessUtil.startProcess(flutterCommand, compileParams);
      if (iOSBuilderSuccess == false){
        throw new CommandRunError("iOS Framework 构建失败: 😞");
      }
    } else {
      final iosBuildLogPath = '${Directory.current.path}/build/ios/frameworkbuild.log';
      final iOSBuilderSuccess = await ProcessUtil.runProcessAndStardandResult(flutterCommand, compileParams, iosBuildLogPath);
      if (iOSBuilderSuccess == false){
        ProcessUtil.iosBuildLogParser(iosBuildLogPath);
        throw new CommandRunError("iOS Framework 构建失败: 😞");
      }
    }

    print('iOS Framework 构建成功 开始整合产物...');


    for (final element in ignoreFrameworks) {
      // final debugDirectory = Directory("$flutterPluginRegistrantPath/Frameworks/Debug/$element.xcframework");
      // if (debugDirectory.existsSync()) {
      //   printYellow('删除：${debugDirectory.path}');
      //   debugDirectory.deleteSync(recursive: true);
      // }
      final releaseDirectory = Directory("$flutterPluginRegistrantPath/Frameworks/Release/$element.xcframework");
      if (releaseDirectory.existsSync()) {
        printYellow('删除：${releaseDirectory.path}');
        releaseDirectory.deleteSync(recursive: true);
      }
    }

    // 移动 APP.xcframeworks 到 GTFlutterAppModule/Frameworks 中
    Directory("$gtFlutterAppModulePath/Frameworks")
        .createSync(recursive: true);
    Directory("$gtFlutterAppModulePath/Frameworks/Debug")
        .createSync(recursive: true);
    Directory("$gtFlutterAppModulePath/Frameworks/Release")
        .createSync(recursive: true);

    // var mvAPPDebugSuccess = await ProcessUtil.startProcess('mv', [
    //   '$flutterPluginRegistrantPath/Frameworks/Debug/App.xcframework',
    //   '$gtFlutterAppModulePath/Frameworks/Debug/App.xcframework'
    // ]);
    // if (!mvAPPDebugSuccess) throw new CommandRunError('Error move APP.xcframework failed.');

    var mvAPPReleaseSuccess = await ProcessUtil.startProcess('mv', [
      '$flutterPluginRegistrantPath/Frameworks/Release/App.xcframework',
      '$gtFlutterAppModulePath/Frameworks/Release/App.xcframework'
    ]);
    if (!mvAPPReleaseSuccess) throw new CommandRunError('Error move APP.xcframework failed.');

    // 整合 Web3 相关组件库
    // Directory("$flutterPluginRegistrantPath/Frameworks/web3_wallet.bundle")
    //     .createSync(recursive: true);
    // var cpWeb3BundleSuccess = await ProcessUtil.startProcess('cp', [
    //   '-rf',
    //   '$flutterPluginRegistrantPath/Frameworks/Release/web3_wallet.xcframework/ios-arm64/web3_wallet.framework/web3_wallet.bundle/',
    //   '$flutterPluginRegistrantPath/Frameworks/web3_wallet.bundle'
    // ]);
    // if (!cpWeb3BundleSuccess) throw new CommandRunError('Copy Web3 Bundle failed.');
    await handlePrivacy(flutterPluginRegistrantPath);
    // 删除 Debug 版本的 xcframework
    var flutterPluginRegistrantDebugPath = Directory('$flutterPluginRegistrantPath/Frameworks/Debug');
    if (flutterPluginRegistrantDebugPath.existsSync()) {
      flutterPluginRegistrantDebugPath.deleteSync(recursive: true);
    }

    // 修改 FlutterPluginRegistrant 版本号
    var flutterPluginRegistrantPodspec = File('$flutterPluginRegistrantPath/FlutterPluginRegistrant.podspec');
    if (!flutterPluginRegistrantPodspec.existsSync()) {
      throw new CommandRunError('FlutterPluginRegistrant.podspec 不存在请确认后再构建！');
    }
    FileUtil.replaceAll(flutterPluginRegistrantPodspec.path,
        "'GateiOSFlutterBuildVersion'", "'$version'");
    print("修改 FlutterPluginRegistrant 版本为 '$version'");

    // 开始整合 APP.xcframework 等
    conformityXCFramework('$gtFlutterAppModulePath/Frameworks');

    var gtFlutterAppModulePathDebugPath = Directory('$gtFlutterAppModulePath/Frameworks/Debug');
    if (gtFlutterAppModulePathDebugPath.existsSync()) {
      gtFlutterAppModulePathDebugPath.deleteSync(recursive: true);
    }

    // 修改 GTFlutterAppModule 版本号
    var appModulePodspecPodspec = File('$gtFlutterAppModulePath/GTFlutterAppModule.podspec');
    if (!appModulePodspecPodspec.existsSync()) {
      throw new CommandRunError('GTFlutterAppModule.podspec 不存在请确认后再构建！');
    }
    FileUtil.replaceAll(appModulePodspecPodspec.path, "'GateiOSFlutterBuildVersion'", "'$version'");
    print("修改 GTFlutterAppModule 版本为 '$version'");

    if (!isUpload) {
      return;
    }

    // 发布 FlutterPluginRegistrant
    final flutterPluginRegistrantSuccess = await ProcessUtil.startProcess("pod", [
      "repo",
      "push",
      "bitbucket-gatebackend-gtspecs",
      "FlutterPluginRegistrant.podspec",
      "--gt"
    ], workingDirectory: flutterPluginRegistrantPath);
    if (!flutterPluginRegistrantSuccess) throw new CommandRunError('FlutterPluginRegistrant 发布失败');
    print("FlutterPluginRegistrant '$version' 发布完成");

    // 发布 GTFlutterAppModule
    final gtFlutterAppModuleSuccess = await ProcessUtil.startProcess("pod", [
      "repo",
      "push",
      "bitbucket-gatebackend-gtspecs",
      "GTFlutterAppModule.podspec",
      "--gt"
    ], workingDirectory: gtFlutterAppModulePath);
    if (!gtFlutterAppModuleSuccess) throw new CommandRunError('GTFlutterAppModule 发布失败');
    print("GTFlutterAppModule '$version' 发布完成");

    print("Flutter iOS 产物发布完成~");
  }

  /// iOS 版本号校验
  Future<void> iosVersionLint(version, workDir, {podName="GTFlutterAppModule"}) async{

    print("开始校验当前版本号是否合法 ...");
    final repoUpdateSuccess = await ProcessUtil.startProcess("pod", [
      "repo",
      "update",
    ], workingDirectory: workDir, printResult: false);
    if (!repoUpdateSuccess) throw new CommandRunError('pod repo update 执行失败');

     await ProcessUtil.startProcess("pod", [
      "version-check",
      podName,
      version
    ], workingDirectory: workDir, printResult: false);

    print("校验完成 ✅");
  }

  /// 整合 XCFramework 产物
  void conformityXCFramework(String dirPath) {
    final files = Directory('$dirPath/Release').listSync();
    for (final file in files) {
      var filename = file.uri.pathSegments.last;
      if (filename.isNullOrEmpty) {
        filename = file.uri.pathSegments[file.uri.pathSegments.length - 2];
      }
      if (!filename.endsWith('.xcframework')) {
        continue;
      }

      final releaseFrameworkPath = "$dirPath/Release/$filename";
      final debugFrameworkPath = "$dirPath/Debug/$filename";

      if (Directory("$debugFrameworkPath/ios-arm64_x86_64-simulator").existsSync()) {
        Directory("$releaseFrameworkPath/ios-arm64_x86_64-simulator")
            .deleteSync(recursive: true);
        Directory("$debugFrameworkPath/ios-arm64_x86_64-simulator")
            .renameSync("$releaseFrameworkPath/ios-arm64_x86_64-simulator");
      }

      if (Directory("$debugFrameworkPath/ios-x86_64-simulator").existsSync()) {
        Directory("$releaseFrameworkPath/ios-x86_64-simulator")
            .deleteSync(recursive: true);
        Directory("$debugFrameworkPath/ios-x86_64-simulator")
            .renameSync("$releaseFrameworkPath/ios-x86_64-simulator");
      }

      print("完成 $releaseFrameworkPath 产物整合");
    }
  }

}
